package util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class Httpmdm {

	public static String mdmSessionIdadmin(String userName,String pws){
		trustAllHosts();
		String urls = Constant.getValue("mdmurladmin").toString();
		URL url;
		String JSESSIONID = null;
		try {
			url = new URL(urls);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
			connection.setDoOutput(true); 
			connection.setDoInput(true);//打开输入，从服务器读取返回数据
			connection.setRequestMethod("POST"); //设置登录模式为POST（字符串大写）
			connection.setInstanceFollowRedirects(false); 
			connection.connect();
			OutputStreamWriter out = new OutputStreamWriter(connection  
					.getOutputStream(), "utf-8");  
			out.write("loginId="+userName+"&password="+pws+""); 
			out.flush();  
			out.close();  
			
			Map<String,List<String>> maps =connection.getHeaderFields();
			List<String> coolist = maps.get("Set-Cookie");  
			JSESSIONID = coolist.get(1).split(";")[0];
			connection.disconnect();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}  
		return JSESSIONID;
	}
	public static String mdmSessionId(String userName,String pws){
		trustAllHosts();
		String urls = Constant.getValue("mdmurl").toString();
		URL url;
		String JSESSIONID = null;
		try {
			url = new URL(urls);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
			connection.setDoOutput(true); 
			connection.setDoInput(true);//打开输入，从服务器读取返回数据
			connection.setRequestMethod("POST"); //设置登录模式为POST（字符串大写）
			connection.setInstanceFollowRedirects(false); 
			connection.connect();
			OutputStreamWriter out = new OutputStreamWriter(connection  
				      .getOutputStream(), "utf-8");  
			out.write("loginId="+userName+"&password="+pws+""); 
			out.flush();  
			out.close();  
			
			Map<String,List<String>> maps =connection.getHeaderFields();
			List<String> coolist = maps.get("Set-Cookie");  
			JSESSIONID = coolist.get(0).split(";")[0];
			connection.disconnect();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}  
		return JSESSIONID;
	}
	
	public static String returnAppList(String JSESSIONID,String deviceId){
		trustAllHosts();
		String surl = Constant.getValue("surl").toString()+"?deviceId="+deviceId;
		URL url;
		String total = ""; 
		try {
			url = new URL(surl);
			HttpURLConnection resumeConnection = (HttpURLConnection) url
		      .openConnection();  
			  resumeConnection.setRequestProperty("Cookie",JSESSIONID);//设置登陆配置	
			resumeConnection.connect();  
			InputStream urlStream = resumeConnection.getInputStream();  
			BufferedReader bufferedReader = new BufferedReader(  
			      new InputStreamReader(urlStream,"UTF-8"));  
			String ss = null;  
			while ((ss = bufferedReader.readLine()) != null) {  
				total += ss;  
			}  
//			IOUtils.write(total, new FileOutputStream("d:/index.html"));  
			bufferedReader.close(); 
			
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} 
		return total;
	}
	
	public static String installApp(String appId,String deviceId,String JSESSIONID){
//		appId = "504";
//		deviceId = "7";
		trustAllHosts();
		String surl = Constant.getValue("appurl")+"?appId="+appId+"&deviceId="+deviceId;
		URL url;
		String total = ""; 
		try {
			url = new URL(surl);
			HttpURLConnection resumeConnection = (HttpURLConnection) url
		      .openConnection();  
			  resumeConnection.setRequestProperty("Cookie",JSESSIONID);//设置登陆配置	
			resumeConnection.connect();  
			InputStream urlStream = resumeConnection.getInputStream();  
			BufferedReader bufferedReader = new BufferedReader(  
			      new InputStreamReader(urlStream,"UTF-8"));  
			String ss = null;  
			while ((ss = bufferedReader.readLine()) != null) {  
				total += ss;  
			}  
			bufferedReader.close(); 
			
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} 
		return total;
	}
	
	public static String addUser(String loginId,String name,String password,String mail,String JSESSIONID){
		trustAllHosts();
		String surl = Constant.getValue("adduserurl")+"?loginId="+loginId+"&name="+name+"" +
				"&password="+password+"&mail="+mail+"&groupIds=-2," +
						"&useGroupRight=1";
		URL url;
		String total = ""; 
		try {
			url = new URL(surl);
			HttpURLConnection resumeConnection = (HttpURLConnection) url
		      .openConnection();  
			resumeConnection.setDoOutput(true); 
			resumeConnection.setDoInput(true); 
			resumeConnection.setRequestMethod("POST"); //设置登录模式为POST（字符串大写）
	        // 配置本次连接的Content-type，配置为application/x-www-form-urlencoded的  
	        // 意思是正文是urlencoded编码过的form参数  
			resumeConnection.setInstanceFollowRedirects(true); 
			resumeConnection.setRequestProperty("Content-Type",  
	                    "application/x-www-form-urlencoded");  
			  resumeConnection.setRequestProperty("Cookie",JSESSIONID);//设置登陆配置	
			resumeConnection.connect();  
			InputStream urlStream = resumeConnection.getInputStream();  
			BufferedReader bufferedReader = new BufferedReader(  
			      new InputStreamReader(urlStream,"UTF-8"));  
			String ss = null;  
			while ((ss = bufferedReader.readLine()) != null) {  
				total += ss;  
			}  
			bufferedReader.close(); 
			
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} 
		return total;
	}
	
	/**
	 * Trust every server - dont check for any certificate
	 */
	public static void trustAllHosts() {
		// Create a trust manager that does not validate certificate chains
		TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
			public java.security.cert.X509Certificate[] getAcceptedIssuers() {
				return new java.security.cert.X509Certificate[] {};
			}

			public void checkClientTrusted(X509Certificate[] chain, String authType) {
			}

			public void checkServerTrusted(X509Certificate[] chain, String authType) {
			}

		} };

		try {
			SSLContext sc = SSLContext.getInstance("TLS");
			sc.init(null, trustAllCerts, new java.security.SecureRandom());
			HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) throws UnsupportedEncodingException{ 
//		System.out.println(installApp("","",mdmSessionId("gls", "123456")));
//		System.out.println(returnAppList(mdmSessionId("gls", "123456"),""));
		System.out.println(addUser("test","test","test","13466571860@139.com",mdmSessionIdadmin("panjiewei", "test")));
//		mdm("panjiewei", "Nqsky1130");\
//		System.out.println(URLEncoder.encode("社区家园"));
//		System.out.println(URLDecoder.decode("%E7%A4%BE%E5%8C%BA%E5%AE%B6%E5%9B%AD"));
	}
}
